#!/usr/bin/python

'''
Main entry
'''

import logging.config
import importlib
import argparse
import configparser
import colorlog
from custom_logging import setup_logging
from process_engine import Engine
from process_engine import Context

def buildContext(args):
    context = Context() 
    config = configparser.ConfigParser();
    config.read("config.ini")
    packagesString = config.get("Tasks", "Packages")
    #load tasks from packages defined in config file
    packages = [package.strip() for package in packagesString.split(",")]
    for packageName in packages:
        if not args or not args.allowPackages or packageName in args.allowPackages:
            p = importlib.import_module(packageName)
            if hasattr(p, "get_tasks"):
                getTasksCall = getattr(p, "get_tasks")
                tasks = getTasksCall()    
                for task in tasks:
                    if not args or not args.allowTasks or task.name in args.allowTasks:
                        context.add_task(task)
    context.finalize_tasks()
    return context

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Program to download data from sources like website.')
    parser.add_argument('-p', action='append', dest='allowPackages', 
                        help='The task packages which are allowed to run. All are allowed if it is not specified.')
    parser.add_argument('-t', action='append', dest='allowTasks', 
                        help='The tasks which are allowed to run. All are allowed if it is not specified.')
    parser.add_argument('-startId', action='store', dest='startId', 
                        help='The start id for the task. All ids smaller than it would be ignored.')
    parser.add_argument('-c', action='append', dest='customParams', 
                        help=r"A customlized parameter with format 'name=value'.")
    setup_logging()

    args = parser.parse_args()
    logger = logging.getLogger(__name__)
    logger.info("%s", args)    
    logger.info("start")
    context = buildContext(args)
    context.args = args
    gatherer = Engine(context)
    allTasks = context.get_tasklist();
    logger.info("going to run %s tasks.\r\n%s", len(allTasks), [task.name for task in allTasks])
    gatherer.start()
    logger.info("finished")

